package cn.com.lms.business.cc.service;


import cn.com.lms.business.cc.persistence.entity.ExamQuestionCategory;
import cn.com.lms.business.cc.persistence.repository.CCQuestionCategoryDao;
import cn.com.lms.business.exam.persistence.entity.QuestionCategory;
import com.bnzj.core.persistence.BaseService;
import com.google.gson.internal.$Gson$Preconditions;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CCQuestionCategoryService extends BaseService<CCQuestionCategoryDao, ExamQuestionCategory, Long> {

    /**
     * 获取一级分类
     * @return
     */
    public List<ExamQuestionCategory> getTree() {
        List<ExamQuestionCategory> all = repository.findAll(Sort.by(Sort.Direction.DESC, "id"));
        List<ExamQuestionCategory> collect = all.stream().filter(item -> {
            return item.getIsDelete() == false && item.getId() == 1;
        }).map(item -> {
            item.setChildren(getChildren(item,all));
            return item;
        }).collect(Collectors.toList());

        return collect;
    }

    /**
     * 获取二、三....级子分类
     * @param examQuestionCategory
     * @param all
     * @return
     */
    public List<ExamQuestionCategory> getChildren(ExamQuestionCategory examQuestionCategory, List<ExamQuestionCategory> all){
        List<ExamQuestionCategory> children = all.stream().filter(item -> {
            return item.getParentId() == examQuestionCategory.getId();
        }).map(item -> {
            item.setChildren(getChildren(item, all));
            return item;
        }).collect(Collectors.toList());
        return children;
    }

    /**
     * 获取子类ID
     * @param categoryId
     * @return
     */
    public List<Long> findChildrensIdByCategoryId(String categoryId) {

        List<ExamQuestionCategory> all = this.findAll(Sort.by(Sort.Direction.ASC, "id"));
        List<Long> childrenIds = new ArrayList<>();
        all.stream().filter(item -> {
            return item.getParentId() == Long.valueOf(categoryId);
        }).forEach(item -> {
            childrenIds.add(item.getId());
            setChildrenIds(item, all, childrenIds);
        });

        return childrenIds;
    }

    public void setChildrenIds(ExamQuestionCategory questionCategory, List<ExamQuestionCategory> all,List<Long> childrenIds){
        all.stream().filter(item -> {
            return item.getParentId().equals(questionCategory.getId());
        }).forEach(item -> {
            childrenIds.add(item.getId());
            setChildrenIds(item, all, childrenIds);
        });
    }
}
